﻿using MahApps.Metro.Controls;
using MahApps.Metro.Controls.Dialogs;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using System.Windows;
using System.Windows.Media;

namespace ScriptManager
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : MetroWindow
    {
        public string user_Key = "";
        public string user_name = "";
        public string user_email = "";
        private string scriptBody = "";
        private int polat = 0;
        DateTime rekvDate = DateTime.Now;
        private static string ApplicationData = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + "\\Logitech\\Logitech Gaming Software\\profiles";
        public MainWindow()
        {
            InitializeComponent();
        }

        private void MetroWindow_Loaded(object sender, RoutedEventArgs e)
        {
            // 加载
            login l = new login(this);
            Hide();
            l.Show();
        }
        public void getrevkDate() {
            functionFactory ff = new functionFactory();
            WebRequest req = WebRequest.Create($"http://warframe.md4.cn:8081/warframeservice/warframeluaSerivce/getrevkDate?userkey={user_Key}");
            WebResponse resp = req.GetResponse();
            StreamReader sr = new StreamReader(resp.GetResponseStream(), Encoding.UTF8);
            string strResponse = sr.ReadToEnd();
            JArray jo = (JArray)JsonConvert.DeserializeObject(strResponse);
            System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
            if (!strResponse.Equals("[]"))
            {
                rekvDate = startTime.AddTicks(long.Parse(jo[0]["rekevdate"].ToString()) * 10000);
                if (rekvDate < DateTime.Now)
                {
                    rekvDateLabel.Content = $"到期时间:{rekvDate.ToString("F")}";
                    rekvDateLabel.Foreground = Brushes.Red;
                }
                else
                {
                    rekvDateLabel.Content = $"到期时间:{rekvDate.ToString("F")}";
                    rekvDateLabel.Foreground = Brushes.Green;
                }
            }
            else
            {
                this.ShowMessageAsync("提示", "未查询到账户包月信息!");
                return;
            }
        }
        public void loadingScript()
        {
            //文件检查

            CheckFeileError();
            //获取点数
            refershPolat();
            //获取到期时间信息
            getrevkDate();
            functionFactory ff = new functionFactory();
            this.ShowMessageAsync("提示", "请注意！窗口关闭会导致宏初始化，配置将会失效!请确保不在使用过程中关闭本程序!");
            infoLabel.Content = $"{user_name} 欢迎使用 当前登录时间为:{DateTime.Now.ToString("F")}   登录设备ID为:{ff.GetMacAddress()}";

        }
        public void CheckFeileError()
        {
            if (File.Exists(ApplicationData) || File.Exists(@"C:\Program Files\Logitech Gaming Software\LCore.exe"))
            {
                // 变更底色
                //加载脚本列表
                functionFactory ff = new functionFactory();
                WebRequest req = WebRequest.Create($"http://warframe.md4.cn:8081/warframeservice/warframeluaSerivce/getScriptList");
                WebResponse resp = req.GetResponse();
                StreamReader sr = new StreamReader(resp.GetResponseStream(), Encoding.UTF8);
                string strResponse = sr.ReadToEnd();
                JArray jo = (JArray)JsonConvert.DeserializeObject(strResponse);
                if (jo.Count > 0)
                {
                    foreach (JObject j in jo)
                    {
                        scriptList.Items.Add(j["scriptName"].ToString());
                    }
                }
                //获取配置文件列表
                DirectoryInfo directoryInfo = new DirectoryInfo(ApplicationData);
                FileInfo[] fs = directoryInfo.GetFiles();
                for (int i = 0; i < fs.Length; i++)
                {
                    FileInfo f = fs[i];
                    Console.WriteLine(f.Name);
                    xmlList.Items.Add(f.Name);
                }
            }
            else
            {
                this.ShowMessageAsync("错误", "未安装Logitech游戏软件或变更了安装位置！\r\n 请重新安装!");
                editorBtn.IsEnabled = false;
            }
        }
        private void MetroWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            //关闭，如果是走的右上角关闭 需要执行登出LoginHis表 
            functionFactory ff = new functionFactory();
            WebRequest req = WebRequest.Create($"http://warframe.md4.cn:8081/warframeservice/warframeluaSerivce/exitApplacation?userkey={user_Key}&mac={ff.GetMacAddress()}");
            WebResponse resp = req.GetResponse();
            StreamReader sr = new StreamReader(resp.GetResponseStream(), Encoding.UTF8);
            string strResponse = sr.ReadToEnd();
            if (strResponse.Equals("1"))
            {
                ff.EditProperty("", $"{ApplicationData}\\{xmlList.SelectedItem}");
                MessageBox.Show("退出成功!", "提示");
            }
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            //加载配置
            if (scriptList.SelectedIndex < 0)
            {
                this.ShowMessageAsync("提示", "未选择任何脚本!");
            }
            else
            {
                WebRequest req = WebRequest.Create($"http://warframe.md4.cn:8081/warframeservice/warframeluaSerivce/getScript?scriptName={scriptList.SelectedItem.ToString()}");
                WebResponse resp = req.GetResponse();
                StreamReader sr = new StreamReader(resp.GetResponseStream(), Encoding.UTF8);
                string strResponse = sr.ReadToEnd();
                JArray jo = (JArray)JsonConvert.DeserializeObject(strResponse);
                scriptBody = jo[0]["scriptBody"].ToString();
                string jsonStr = jo[0]["scriptProperty"].ToString();
                editProperty(jsonStr);
            }
        }
        private void editProperty(string jsonStr)
        {
            JObject jo = (JObject)JsonConvert.DeserializeObject(jsonStr);
            JArray array = (JArray)jo["Paramet"];
            List<object> aList = new List<object>();
            foreach (var jObject in array)
            {
                propertyInfo property = new propertyInfo();
                property.name = jObject["descp"].ToString();
                property.value = jObject["Value"].ToString();
                property.id = jObject["Name"].ToString();
                aList.Add(property);

            }
            propertyDataGrid.ItemsSource = aList;
            propertyDataGrid.AutoGenerateColumns = false;
            propertyDataGrid.CanUserAddRows = false;

        }

        private void editorBtn_Click(object sender, RoutedEventArgs e)
        {
            functionFactory ff = new functionFactory();
            //写入按钮 
            if (scriptList.SelectedIndex < 0 || xmlList.SelectedIndex < 0)
            {
                this.ShowMessageAsync("错误", "未选中脚本或配置文件!");
            }
            else if (propertyDataGrid.Items.Count < 1)
            {
                this.ShowMessageAsync("错误", "未加载配置项!");
            }
            else
            {
                //开始写入
                this.ShowMessageAsync("提示", "正在获取配置和脚本，请耐心等待~");
                string property_str = "";
                foreach (propertyInfo property in propertyDataGrid.Items)
                {
                    property_str += $"{property.id}={property.value}\r\n";
                }
                //获取原始
                property_str += scriptBody;
                //this.ShowMessageAsync("代码",ff.strToChar(property_str)); //测试正确 需要拼接
                string all = ff.strToChar(property_str);
                //this.ShowMessageAsync("", all);
                ff.EditProperty(all,$"{ApplicationData}\\{xmlList.SelectedItem.ToString()}");

            }
        }

        private void cdk_Click(object sender, RoutedEventArgs e)
        {
            //CDK兑换 打开新窗口完事
            cdkRes res = new cdkRes(this);
            res.userKey = this.user_Key;
            res.Title = $"CDK兑换       {polatLabel.Content}";
            res.polat = this.polat;
            res.Show();
        }
        public void refershPolat()
        {
            //刷新点数
            WebRequest req = WebRequest.Create($"http://warframe.md4.cn:8081/warframeservice/warframeluaSerivce/queryPloat?userKey={user_Key}");
            WebResponse resp = req.GetResponse();
            StreamReader sr = new StreamReader(resp.GetResponseStream(), Encoding.UTF8);
            string strResponse = sr.ReadToEnd();
            JArray jo = (JArray)JsonConvert.DeserializeObject(strResponse);
            polat = int.Parse(jo[0]["polat"].ToString());
            polatLabel.Content = $"当前点数:{polat}";
        }
    }
}
